package gov.pbc.gx.nn.pz.bdf.service;

import gov.pbc.gx.nn.pz.bdf.entity.Dept;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;




import com.bstek.bdf2.core.CoreJdbcDao;
import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.model.DefaultDept;
import com.bstek.bdf2.core.service.IDeptService;


public class DeptService extends CoreJdbcDao implements IDeptService {

	@Override
	public IDept loadDeptById(String deptId) {
		// TODO Auto-generated method stub
		String sql = "SELECT D.ID_,D.NAME_,D.DESC_,D.COMPANY_ID_,D.PARENT_ID_,D.CODE_,D.TYPE_,D.KIND_,D.ORDER_ FROM T_DEPT D WHERE D.ID_=?";
		List<IDept> depts=this.getJdbcTemplate().query(sql,new Object[]{deptId},new DefaultDeptRowMapper());
		if(depts.size()==0){ 
			return null;			
		}else{
			return depts.get(0);
		}
	}

	@Override
	public List<IDept> loadDeptsByParentId(String parentId,String companyId) {
		String sql="SELECT D.ID_,D.NAME_,D.DESC_,D.COMPANY_ID_,D.PARENT_ID_,D.CODE_,D.TYPE_,D.KIND_,D.ORDER_ FROM T_DEPT D WHERE D.COMPANY_ID_=?";
		if(parentId==null){
			sql+=" AND D.PARENT_ID_ IS NULL";
			return this.getJdbcTemplate().query(sql,new Object[]{companyId},new DefaultDeptRowMapper());
		}else{
			sql+=" AND D.PARENT_ID_=?";			
			return this.getJdbcTemplate().query(sql, new Object[]{companyId,parentId},new DefaultDeptRowMapper());
		}	
	}

	@Override
	public List<IDept> loadUserDepts(String username) {
		// TODO Auto-generated method stub
		String sql = "SELECT D.ID_,D.NAME_,D.DESC_,D.COMPANY_ID_,D.PARENT_ID_,D.CODE_,D.TYPE_,D.KIND_,D.ORDER_ FROM BDF2_USER_DEPT UD INNER JOIN T_DEPT D ON UD.DEPT_ID_=D.ID_ WHERE UD.USERNAME_=?";
		List<IDept> depts = this.getJdbcTemplate().query(sql,
				new Object[] { username }, new DefaultDeptRowMapper());
		for (IDept dept : depts) {
			this.buildParentDept(dept);
		}
		return depts;
	}

	@Override
	public IDept newDeptInstance(String deptId) {
		// TODO Auto-generated method stub
		return new DefaultDept(deptId);
	}

	private void buildParentDept(IDept dept){
		Dept depts=(Dept) dept;
		if(StringUtils.isNotEmpty(depts.getParentId())){
			IDept parentDept=this.loadDeptById(depts.getParentId());
			depts.setParent(parentDept);
			this.buildParentDept(parentDept);
		}
	}

	class DefaultDeptRowMapper implements RowMapper<IDept> {
		public Dept mapRow(ResultSet rs, int rowNum) throws SQLException {
			Dept d = new Dept();
			d.setId(rs.getString("ID_"));
			d.setName(rs.getString("NAME_"));
			d.setDesc(rs.getString("DESC_"));
			d.setCompanyId(rs.getString("COMPANY_ID_"));
			d.setParentId(rs.getString("PARENT_ID_"));
			d.setType((rs.getInt("TYPE_")));
			d.setCode(rs.getString("CODE_"));
			d.setKind(rs.getInt("KIND_"));
			d.setOrder(rs.getInt("ORDER_"));
			return d;
		}
	}

}
